<!--
 * @Descripttion: 满减返佣
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2021-04-29 14:16:04
-->
<template>
  <div class="lb-sys-sproconfig">
    <top-nav></top-nav>
    <div class="page-main">
      <el-row class="page-top-operate">
        <lb-button
          size="medium"
          type="primary"
          @click="$router.push('/app/reduction/edit')"
          icon="el-icon-plus"
          >{{ $t('menu.ReductionAdd') }}</lb-button
        >
      </el-row>
      <div class="page-search-form">
        <el-form
          @submit.native.prevent
          :inline="true"
          :model="searchForm"
          ref="searchForm"
        >
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="searchForm.title"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('searchForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column prop="id" width="80" label="ID"> </el-table-column>
        <el-table-column
          prop="title"
          width="150"
          show-overflow-tooltip
          label="标题"
        >
        </el-table-column>
        <el-table-column prop="full" label="满/减">
          <template slot-scope="scope">
            <div>满{{ scope.row.full }}减¥{{ scope.row.reduction }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="over_time" label="使用有效期">
          <template slot-scope="scope">
            <div>{{ scope.row.over_time }}天</div>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="剩余｜总量">
          <template slot-scope="scope">
            <div>
              {{
                scope.row.num - scope.row.get_num + '张 | ' + scope.row.num
              }}张
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="create_user_text" label="可用公司/部门">
          <template slot-scope="scope">
            <div>{{ scope.row.company_num }}个</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="table-operate">
              <!-- status -1已领完，0已停止，1发放中- -->
              <lb-button
                size="mini"
                plain
                type="primary"
                @click="$router.push('/app/reduction/edit?id=' + scope.row.id)"
                >{{ $t('action.edit') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="danger"
                @click="toEnd(scope.row.id, scope.row.status)"
                >{{
                  $t(
                    scope.row.status === 0
                      ? 'action.startProvide'
                      : 'action.stopProvide'
                  )
                }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                :type="scope.row.status === 0 ? '' : 'danger'"
                :disabled="scope.row.status === 0"
                @click="toDownload(scope.row.id)"
                >{{ $t('action.downloadCode') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="success"
                @click="
                  $router.push('/app/reduction/record?id=' + scope.row.id)
                "
                >{{ $t('menu.ReductionRecord') }}</lb-button
              >
              <lb-button
                size="mini"
                plain
                type="warning"
                @click="
                  $router.push('/app/reduction/receive?id=' + scope.row.id)
                "
                >{{ $t('menu.ReductionReceive') }}</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :batch="false"
        :page="searchForm.page"
        :pageSize="searchForm.limit"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
      </lb-page>

      <el-dialog
        title="下载推广码"
        :visible.sync="downloadDialog"
        width="400px"
        center
      >
        <div class="dialog-inner">
          <el-form @submit.native.prevent label-width="80px">
            <el-form-item label="员工">
              <el-select
                v-model="downloadForm.staff_id"
                @change="getQrCode"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in staffArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <lb-image
            v-loading="imgLoading"
            :src="reductionSrc"
            v-if="reductionSrc"
          ></lb-image>
          <lb-image
            v-loading="imgLoading"
            src="https://lbqny.migugu.com/admin/public/default.jpg"
            v-else
          ></lb-image>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="downloadDialog = false">{{
            $t('action.cancel')
          }}</el-button>
          <el-button type="primary" @click="downloadReduction">下载</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      searchForm: {
        title: '',
        limit: 10,
        page: 1
      },
      total: 0,
      tableData: [],
      downloadDialog: false,
      staffArr: [],
      downloadForm: {
        id: '',
        staff_id: '',
        page: 'reduction/pages/detail'
      },
      reductionSrc: ''
    }
  },
  created () {
  },
  activated () {
    this.getTableDataList()
  },
  methods: {
    resetForm (name) {
      this.$refs[name].resetFields()
      this.getTableDataList(1)
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    async getTableDataList (flag) {
      if (flag) {
        this.searchForm.page = 1
        this.tableData = []
      }
      this.loading = true
      let { searchForm } = this
      let { code, data } = await this.$api.reductionActiveList(searchForm)
      this.loading = false
      if (code !== 200) return
      this.tableData = data.data
      this.total = data.total
    },
    getQrCode () {
      this.imgLoading = true
      this.$api.reductionCouponShareQr(this.downloadForm).then(res => {
        this.imgLoading = false
        if (res.code === 200) {
          this.reductionSrc = res.data
        }
      })
    },
    downloadReduction () {
      if (!this.reductionSrc) {
        this.$message.error('没有推广码可以下载！')
      } else {
        this.downloadImg(this.reductionSrc, '推广码')
      }
    },
    /**
     * @method 下载图片
     */
    downloadImg (imgsrc, name) {
      this.$api.handleImgSrc(imgsrc).then(res => {
        let image = new Image()
        // 解决跨域 Canvas 污染问题
        image.setAttribute('crossOrigin', 'anonymous')
        image.onload = function () {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          let context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          let url = canvas.toDataURL() // 得到图片的base64编码数据

          let a = document.createElement('a') // 生成一个a元素
          let event = new MouseEvent('click') // 创建一个单击事件
          a.download = name || 'photo' // 设置图片名称
          a.href = url // 将生成的URL设置为a.href属性
          a.dispatchEvent(event) // 触发a的单击事件
        }
        image.src = res
      })
    },
    async toDownload (id) {
      let res = await this.$api.reductionGetStaffInfo({ active_id: id })
      this.staffArr = res.data
      this.downloadForm.id = id
      this.downloadForm.staff_id = ''
      this.reductionSrc = ''
      this.downloadDialog = true
    },
    async toEnd (id, status) {
      let confirmText = this.$t(status === 0 ? 'tips.confirmStartProvide' : 'tips.confirmStopProvide')
      this.$confirm(confirmText, this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.toConfirmEnd(id, status)
      }).catch(() => {

      })
    },
    async toConfirmEnd (id, status) {
      let { code } = await this.$api.reductionStopActive({ id, status: status === 0 ? 1 : 0 })
      if (code !== 200) return
      this.$message.success(this.$t('tips.successOper'))
      this.tableData = []
      this.getTableDataList()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-input,
.el-select {
  width: 200px;
}
.dialog-inner {
  height: 300px;
  .el-image {
    width: 200px;
    height: 200px;
    margin: 0 auto;
  }
}
</style>
